<?php

namespace think\filesystem\driver;

use League\Flysystem\Config;
use think\filesystem\Adapter\QiniuAdapter;
use think\filesystem\Driver;

class Qiniu extends Driver
{
    /**
     * 配置参数
     * @var array
     */
    protected $config = [
        "accessKey" => "",
        "secretKey" => "",
        "bucket" => "",
        "domain" => "https://up-z1.qiniup.com",
        "cdn" => ""
    ];

    protected function createAdapter(): QiniuAdapter
    {
        return new QiniuAdapter($this->config);
    }

    /**
     * 保存文件
     * @param string $path 路径
     * @param $file
     * @param null|string|\Closure $rule 文件名规则
     * @param array $options 参数
     * @return string
     */
    public function putFile(string $path, $file, $rule = null, array $options = [])
    {
        return $this->putFileAs($path, $file, $file->hashName($rule), $options);
    }

    /**
     * 指定文件名保存文件
     * @param string $path 路径
     * @param $file
     * @param string $name 文件名
     * @param array $options 参数
     * @return string
     */
    public function putFileAs(string $path, $file, string $name, array $options = [])
    {
        $path = trim($path . '/' . $name, '/');
        $this->put($path, $file, $options);
        return $this->createAdapter()->getUrl($path);
    }

    /**
     * 保存文件
     * @param string $path 路径
     * @param $contents
     * @param array $options 参数
     * @return bool
     */
    public function put(string $path, $contents, array $options = [])
    {
        //字符串
        if (is_string($contents)) {
            $this->createAdapter()->write($path, $contents, new Config($options));
        }
        //文件
        if (is_file($contents)) {
            $contents = fopen($contents->getRealPath(), 'r');
            $this->createAdapter()->writeStream($path, $contents, new Config($options));
            fclose($contents);
        }
        //资源
        if (is_resource($contents)) {
            $this->createAdapter()->writeStream($path, $contents, new Config($options));
            fclose($contents);
        }
        return true;
    }

    /**
     * 获取文件访问地址
     * @param string $path 文件路径
     * @return string
     */
    public function url(string $path): string
    {
        return $this->createAdapter()->getUrl($path);
    }

    /**
     * 调用adapter方法
     * @param $method
     * @param $parameters
     * @return mixed
     */
    public function __call($method, $parameters)
    {
        return $this->createAdapter()->$method(...$parameters);
    }

}